package com.game.core.net.server;

import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;

import java.util.concurrent.atomic.AtomicInteger;

import com.game.core.net.handler.AbstractMessageInitializer;
import com.game.core.net.handler.BaseMessageHandler;
import com.game.core.net.handler.MessageProcessor;
import com.game.core.net.handler.SnappyFramedCodec;
import com.kodgames.core.net.handler.UdpCoder;
import com.game.core.net.message.InternalMessage;

public class SimpleUdpInitializer extends ChannelInitializer<Channel>
{
	static AtomicInteger handlerId=new AtomicInteger(0);
	AbstractMessageInitializer messageInitializer;
	MessageProcessor messageProcess;
	SnappyFramedCodec snappyFramedCodec;
	UdpCoder udpcoder;

	public SimpleUdpInitializer(AbstractMessageInitializer messageInitializer)
	{
		this.messageInitializer = messageInitializer;
		messageProcess = new MessageProcessor(messageInitializer);
		snappyFramedCodec = new SnappyFramedCodec();
		udpcoder = new UdpCoder(messageProcess, true);
	}

	@Override
	protected void initChannel(Channel ch)
		throws Exception
	{
		ChannelPipeline p = ch.pipeline();
		String nameId="-"+handlerId.incrementAndGet();
		p.addLast("UdpDecoder"+nameId, udpcoder);
		//udp自己切片，不需要LengthFieldBasedFrameDecoder和LengthFieldPrepender
		//p.addLast("FrameDecoder"+nameId,new LengthFieldBasedFrameDecoder(204800, 0, 4, 0, 4));
		//p.addLast("LengthFieldPrepender"+nameId, lengthFieldPrepender);
		p.addLast("SnappyFramedCodec"+nameId, snappyFramedCodec);
		p.addLast("MessageProcessor"+nameId, messageProcess);
	}
	
	/**
	 * 服务器内部通过消息机制传递数据
	 * @param handler
	 * @param protocol
	 */
	public void readMessageBySelf(final BaseMessageHandler<?> handler, final InternalMessage protocol)
	{
		messageProcess.readMessage(handler, protocol);
	}
}
